package org.wkg.lesson07;

public class MyBlockingQueue01 {
    private Integer[] elementData;
    private volatile int head;
    private volatile int tail;
    private volatile int size;

    public MyBlockingQueue01(int capacity) {
        if (capacity <= 0) {
            throw new IllegalArgumentException("队列容量必须大于0");
        }
        elementData = new Integer[capacity];
    }

    public void put(Integer value) throws InterruptedException {
        synchronized (this) {
            //为什么不是这个判断队列已满tail >= size
            while (size >= elementData.length) {
                this.wait();
            }
            elementData[tail] = value;
            tail++;
            if (tail >= elementData.length) {//为什么不是tail > elementData.length
                tail = 0;
            }
            size++;
            this.notifyAll();
        }
    }

    public synchronized Integer take() throws InterruptedException {
        while (size == 0) {
            this.wait();
        }
        Integer value = elementData[head];
        head++;
        if (head >= elementData.length) {//为什么不是head > elementData.length
            head = 0;
        }
        size--;
        this.notifyAll(); //此时notifyAll是直接唤醒所有阻塞线程然后运行阻塞线程还是等把这个方法内容全部执行完以后才去执行阻塞线程
        return value;
    }
}
